package com.scau.security;

import com.alibaba.fastjson.JSONObject;
import com.scau.dto.CBECReturn;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.scau.handleException.ResultCode.USER_INFO_ERROR;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        System.out.println("preHandle");
        String token = request.getHeader("token");
        System.out.println(token);

        String temp = request.getParameter("token");
        System.out.println(temp);
        if(null!=token) {
            String username = Jwt.unsign(token, String.class);
            String reUsername = request.getParameter("username");
            if (null != username) {
                if (username.equals(reUsername)) {
                    return true;
                } else {
                    responseMessage(response,response.getWriter());
                    return false;
                }
            } else {
                responseMessage(response,response.getWriter());
                return false;
            }

        }else {
            responseMessage(response,response.getWriter());
            return false;
        }
    }

    private void responseMessage(HttpServletResponse response, PrintWriter out) {
        CBECReturn cbecReturn = CBECReturn.build(USER_INFO_ERROR);
        response.setContentType("application/json; charset=utf-8");
        String json = JSONObject.toJSONString(cbecReturn);
        out.print(json);
        out.flush();
        out.close();
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
